<?php

namespace App\Http\Services\FormBuilder\Elements;

abstract class FormControl extends Element
{
    public $fillable = [
        'id', 'name', 'type', 'placeholder'
    ];

    protected $attributes = [
        'class' => 'form-control',
    ];

    protected $hasError = false;

    public function __construct($option=[])
    {

        $this->renderOption($option);
    }

    protected function setName($name)
    {
        $this->setAttribute('name', $name);
    }

    public function required()
    {
        $this->setAttribute('required', 'required');

        return $this;
    }

    public function optional()
    {
        $this->removeAttribute('required');

        return $this;
    }

    public function disable()
    {
        $this->setAttribute('disabled', 'disabled');

        return $this;
    }

    public function enable()
    {
        $this->removeAttribute('disabled');

        return $this;
    }

    public function autofocus()
    {
        $this->setAttribute('autofocus', 'autofocus');

        return $this;
    }

    public function unfocus()
    {
        $this->removeAttribute('autofocus');

        return $this;
    }

    public function setError($error = true)
    {
        $this->hasError = $error;

        return $this;
    }

    public function hasError()
    {
        return $this->hasError;
    }

    public function editBlock()
    {
        $require = (int)$this->getAttribute('require');
        $seconds = (int)$this->getAttribute('seconds');
        $step = $this->getAttribute('step');

        $type = $this->getAttribute('type');
        $label = (new Label($this->getAttribute('display_name')))
            ->forId($this->getAttribute('id'))
            ->required($require);
        $tips  = (new HelpBlock($this->getAttribute('tips')));
        if ($require) {
            $this->addClass('required');
        }

        if ($type == 'number') {
            $this->addClass('number');
            if (empty($step)) $step=1;
            $this->setAttribute('step',$step);
        }

        if ($seconds) {
            $this->addClass('seconds');
        }
        $field = (new Field($label, $this, $tips))
            ->addClass($this->getAttribute('li_class'))
            ->render();

        return $field;

    }


    public function detailBlock()
    {
        $class = $this->getAttribute('li_class');
        $displayName = $this->getAttribute('display_name');
        $value = $this->getAttribute('value');
        if (is_array($value)) {
            $value = ltrim(implode('/ ',$value),'/ ');
        }
        $html = '';
        $html .= '<div class="items '.$class.'">';
        $html .= '<label class="'.$class.'">'.$displayName.'</label>';
        $html .= '<div class="detail '.$class.'">'.$value.'</div>';
        $html .='</div>';

        return $html;
    }
}
